<?php

namespace app\services;

use plugin\admin\app\model\Order;
use plugin\admin\app\model\Reservation;
use plugin\admin\app\model\UserAddress;

class ReservationService
{
    public static function add($data)
    {
        $addressInfo = UserAddress::where('id', $data['address_id'])->first();

        if (!$addressInfo) {
            throw new \Exception('不存在的地址');
        }

        $orderNo = OrderService::generateOrderNo();

        $insertData = [
            'user_id' => get_user_id(),
            'order_no' => $orderNo,
            'name' => $data['name'],
            'thumbs' => json_encode($data['thumbs'], JSON_UNESCAPED_UNICODE),
            'weight' => $data['weight'],
            'date' => $data['date'],
            'time_range' => $data['time_range'],
            'address_info' => json_encode($addressInfo, JSON_UNESCAPED_UNICODE),
            'status' => Reservation::STATUS_WAIT,
            'created_time' => date('Y-m-d H:i:s'),
        ];

        Reservation::insert($insertData);

        Order::insert([
            'user_id' => get_user_id(),
            'order_no' => $orderNo,
            'price' => 0,
            'pay_way' => 'wechat',
            'remark' => $data['remark'] ?? '',
            'status' => Order::STATUS_WAITING_SHIPPING,
            'created_time' => date('Y-m-d H:i:s'),
            'type' => Order::TYPE_RESERVATION
        ]);
    }
}